package adminAction;

import com.jspsmart.upload.Request;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import dao.BookDao;
import po.Book;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@WebServlet(urlPatterns = "/admin/adminAction/ProductAddServlet")
public class ProductAddServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        SmartUpload su = new SmartUpload();
        //初始化
        su.initialize(this.getServletConfig(),req,resp);

        //上传过程
        try {
            su.upload();

        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //获取上传的文件对象
        Request request = su.getRequest();
        String isbn = request.getParameter("isbn");
        String path = "../img/goods/"+isbn;
        File file = new File(path);
        file.mkdirs();
        try {
            su.save(path);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        Double price = Double.parseDouble(request.getParameter("price"));
        Integer pages = Integer.parseInt(request.getParameter("pages"));
        Integer words = Integer.parseInt(request.getParameter("words"));
        String press = request.getParameter("press");
        Integer edition = Integer.parseInt(request.getParameter("edition"));
        String form = request.getParameter("form");
        String format = request.getParameter("format");
        String packaging = request.getParameter("packaging");
        Book book = new Book();
        book.setPrice(price);
        book.setIsbn(isbn);
        book.setTitle(title);
        book.setPackaging(packaging);
        book.setPages(pages);
        book.setPress(press);
        book.setWords(words);
        book.setAuthor(author);
        book.setFormat(format);
        book.setForm(form);
        book.setEdition(edition);
        BookDao bookDao = new BookDao();
        Integer row = bookDao.insert(book);
        if (row>0){
            req.getRequestDispatcher("../page/product-list.jsp").forward(req,resp);
        }else {
            req.getRequestDispatcher("../page/product-add.jsp").forward(req,resp);
        }
    }
}
